package org.frog.sgs.server.game;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.mina.core.session.IoSession;
import org.frog.sgs.character.Character;
import org.frog.sgs.consts.Constants;
import org.frog.sgs.event.SgsEventCode;
import org.frog.sgs.io.SgsMsg;
import org.frog.sgs.server.game.status.ServerStatus;
import org.frog.sgs.server.msg.ServerMsgBroadcast;
import org.frog.sgs.server.msg.ServerMsgDisableLogin;

/**
 * @author duanxiangqi
 * @date 2012-10-23
 */
public class ServerCharacterManager {

	private ServerInstance instance;

	private List<Character> characters = new ArrayList<Character>();

	//当前是哪个玩家的回合阶段
	private Character currentCharacter;

	public ServerCharacterManager(ServerInstance instance) {
		this.instance = instance;
	}

	public void enter(IoSession session) {
		// 游戏Status为等待玩家进入，并且玩家未满时才允许加入。
		if (instance.getStatus() != ServerStatus.waitingCharacter) {
			System.err.println("游戏当前状态是" + instance.getStatus() + "，禁止玩家进入");
			session.write(new ServerMsgDisableLogin());
			session.close(false);
		} else if (!canEnter()) {
			System.err.println("游戏人数已满！");
			session.write(new ServerMsgDisableLogin());
			session.close(false);
		} else {
			Character character = new Character();
			character.setSession(session);
			character.setInstance(instance);
			character.init();
			session.setAttribute(Constants.SESSION_KEY_CHARACTER, character);
			characters.add(character);
			String msg = "欢迎玩家【" + session.getRemoteAddress() + "】加入游戏";
			sendMsgToAll(new ServerMsgBroadcast(msg));
			if (characters.size() == instance.getConfig().getPlayerNum()) {
				instance.start();
			}
		}
	}

	public void leave(IoSession session) throws Exception {
		Character character = (Character) session.getAttribute(Constants.SESSION_KEY_CHARACTER);
		if (character == null) {
			return;
		}
		if (instance.isBeforePlaying()) {
			// 游戏开始前玩家断开连接，视为离开游戏，删除角色
			characters.remove(character);
			String msg = "玩家【" + session.getRemoteAddress() + "】离开游戏";
			sendMsgToAll(new ServerMsgBroadcast(msg));
		} else if (instance.isPlaying()) {
			// 游戏进行中玩家断开连接，视为【逃离状态】，游戏进程不受影响，角色执行默认相应操作
			character.setSession(null);
			String msg = "玩家【" + session.getRemoteAddress() + "】逃离了游戏";
			System.out.println(msg);
			sendMsgToAll(new ServerMsgBroadcast(msg));
			if (character.getCurrentEventCode() == SgsEventCode.CHOOSE_GENERAL_OVER
					|| getZhuGong().getCurrentEventCode() == SgsEventCode.CHOOSE_GENERAL_OVER) {
				// 等待选择将领或等待主公选择将领
				character.chooseGeneralOver(null);
			}
			List<Character> characters = instance.getCharacterManager().getCharacters();
			boolean isOver = true;
			for (Character character2 : characters) {
				if (character2.getSession() != null) {
					isOver = false;
					break;
				}
			}
			if (isOver) {
				System.err.println("玩家全部退出，游戏结束");
				System.exit(0);
			}
		} else {
			// 游戏结束后玩家断开连接，视为离开游戏，删除角色
			characters.remove(character);
			String msg = "玩家【" + session.getRemoteAddress() + "】离开游戏";
			System.out.println(msg);
			sendMsgToAll(new ServerMsgBroadcast(msg));
		}
	}

	public void sendMsgToAll(SgsMsg msg) {
		for (Character character : characters) {
			character.sendMsg(msg);
		}
	}

	public Character getZhuGong() {
		for (Character character : characters) {
			if (character.getRole().isZhugong()) {
				return character;
			}
		}
		return null;
	}

	public void shuffle() {
		Collections.shuffle(characters);
		for (int i = 0; i < characters.size(); i++) {
			Character character = characters.get(i);
			character.setPosition(i);
		}
		System.out.println("随机打乱玩家位置");
	}

	public Character getByPosition(int position) {
		for (Character character : characters) {
			if (character.getPosition() == position) {
				return character;
			}
		}
		return null;
	}

	public boolean canEnter() {
		return characters.size() < instance.getConfig().getPlayerNum();
	}

	public ServerInstance getInstance() {
		return instance;
	}

	public void setInstance(ServerInstance instance) {
		this.instance = instance;
	}

	public List<Character> getCharacters() {
		return characters;
	}

	public Character getCurrentCharacter() {
		return currentCharacter;
	}

	public void setCurrentCharacter(Character currentCharacter) {
		this.currentCharacter = currentCharacter;
	}
}
